<template>
    <div class="app-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="学校">
          <el-input v-model="searchForm.university" placeholder="请输入学校"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="success" @click="openAddDialog">新增</el-button>
        </el-form-item>
      </el-form>
  
      <el-table :data="students" style="width: 100%">
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="university" label="学校" width="180"></el-table-column>
        <el-table-column prop="major" label="专业" width="180"></el-table-column>
        <el-table-column prop="college" label="学院" width="180"></el-table-column>
        <el-table-column label="出生年月" width="120">
          <template slot-scope="scope">
            {{ formatDate(scope.row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="politicalStatus" label="政治面貌" width="180"></el-table-column>
        <el-table-column prop="healthStatus" label="健康状况" width="100">
          <template slot-scope="scope">
            {{ scope.row.healthStatus.slice(0, 5) }}{{ scope.row.healthStatus.length > 5 ? '...' : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="nativePlace" label="生源地区" width="180"></el-table-column>
        <el-table-column label="入学时间" width="120">
          <template slot-scope="scope">
            {{ formatDate(scope.row.enrollmentDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="contactAddress" label="通讯地址" width="200"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <span class="action-button" @click="handleEdit(scope.$index, scope.row)">修改</span>
            <span class="action-button delete-button" @click="handleDelete(scope.$index, scope.row.studentId)">删除</span>
          </template>
        </el-table-column>
      </el-table>
  
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
  
      <!-- 新增学生对话框 -->
      <el-dialog title="新增学生" :visible.sync="dialogVisible" width="50%" custom-class="custom-dialog">
        <el-form :model="newStudent" :rules="rules" ref="newStudentForm" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号用户" prop="userId">
                <el-select v-model="newStudent.userId" placeholder="请选择账号用户" class="uniform-input">
                    <el-option v-for="user in users" :key="user.userId" :label="user.userName" :value="user.userId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="newStudent.name" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="newStudent.gender" placeholder="请选择性别" class="uniform-input">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="出生年月" prop="birthDate">
                <el-date-picker
                  v-model="newStudent.birthDate"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  class="uniform-input">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入学时间" prop="enrollmentDate">
                <el-date-picker
                  v-model="newStudent.enrollmentDate"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  class="uniform-input">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="生源地区" prop="nativePlace">
                <el-input v-model="newStudent.nativePlace" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="通讯地址" prop="contactAddress">
                <el-input v-model="newStudent.contactAddress" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="政治面貌" prop="politicalStatus">
                <el-select v-model="newStudent.politicalStatus" placeholder="请选择政治面貌" class="uniform-input">
                  <el-option label="共青团员" value="共青团员"></el-option>
                  <el-option label="中共党员" value="中共党员"></el-option>
                  <el-option label="中共预备党员" value="中共预备党员"></el-option>
                  <el-option label="群众" value="群众"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="健康状况" prop="healthStatus">
                <el-select v-model="newStudent.healthStatus" placeholder="请选择健康状况" class="uniform-input">
                  <el-option label="健康" value="健康"></el-option>
                  <el-option label="亚健康" value="亚健康"></el-option>
                  <el-option label="疾病" value="疾病"></el-option>
                  <el-option label="残疾" value="残疾"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="学校" prop="university">
                <el-input v-model="newStudent.university" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="专业" prop="major">
                <el-input v-model="newStudent.major" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="学院" prop="college">
                <el-input v-model="newStudent.college" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addStudent">确定</el-button>
        </span>
      </el-dialog>
  
      <!-- 修改学生对话框 -->
      <el-dialog title="修改学生" :visible.sync="editDialogVisible" width="50%" custom-class="custom-dialog">
        <el-form :model="editingStudent" :rules="rules" ref="editingStudentForm" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号用户" prop="userId">
                <el-select v-model="editingStudent.userId" placeholder="请选择账号用户" class="uniform-input">
                  <el-option v-for="user in users" :key="user.userId" :label="user.userName" :value="user.userId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="editingStudent.name" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="editingStudent.gender" placeholder="请选择性别" class="uniform-input">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="出生年月" prop="birthDate">
                <el-date-picker
                  v-model="editingStudent.birthDate"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  class="uniform-input">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入学时间" prop="enrollmentDate">
                <el-date-picker
                  v-model="editingStudent.enrollmentDate"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  class="uniform-input">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="生源地区" prop="nativePlace">
                <el-input v-model="editingStudent.nativePlace" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="通讯地址" prop="contactAddress">
                <el-input v-model="editingStudent.contactAddress" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="政治面貌" prop="politicalStatus">
                <el-select v-model="editingStudent.politicalStatus" placeholder="请选择政治面貌" class="uniform-input">
                  <el-option label="共青团员" value="共青团员"></el-option>
                  <el-option label="中共党员" value="中共党员"></el-option>
                  <el-option label="中共预备党员" value="中共预备党员"></el-option>
                  <el-option label="群众" value="群众"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="健康状况" prop="healthStatus">
                <el-select v-model="editingStudent.healthStatus" placeholder="请选择健康状况" class="uniform-input">
                  <el-option label="健康" value="健康"></el-option>
                  <el-option label="亚健康" value="亚健康"></el-option>
                  <el-option label="疾病" value="疾病"></el-option>
                  <el-option label="残疾" value="残疾"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="学校" prop="university">
                <el-input v-model="editingStudent.university" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="专业" prop="major">
                <el-input v-model="editingStudent.major" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="right-column">
              <el-form-item label="学院" prop="college">
                <el-input v-model="editingStudent.college" class="uniform-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateStudent">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getStudents, saveOrUpdateStudent, deleteStudent } from '@/api/student/student';
  import { studentUserList } from '@/api/system/user'; // 更新导入路径
  
  export default {
    data() {
      return {
        students: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        searchForm: {
          name: '',
          university: ''
        },
        dialogVisible: false,
        editDialogVisible: false,
        newStudent: {
          userId: '',
          name: '',
          gender: '',
          university: '',
          major: '',
          college: '',
          birthDate: '',
          politicalStatus: '',
          healthStatus: '',
          nativePlace: '',
          enrollmentDate: '',
          contactAddress: ''
        },
        editingStudent: {
          id: '',
          userId: '',
          name: '',
          gender: '',
          university: '',
          major: '',
          college: '',
          birthDate: '',
          politicalStatus: '',
          healthStatus: '',
          nativePlace: '',
          enrollmentDate: '',
          contactAddress: ''
        },
        rules: {
          userId: [{ required: true, message: '请选择账号用户', trigger: 'change' }],
          name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
          university: [{ required: true, message: '请输入学校', trigger: 'blur' }],
          major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
          college: [{ required: true, message: '请输入学院', trigger: 'blur' }],
          birthDate: [{ required: true, message: '请选择出生年月', trigger: 'change' }],
          enrollmentDate: [{ required: true, message: '请选择入学时间', trigger: 'change' }]
        },
        users: []
      };
    },
    created() {
      this.fetchStudents();
      this.fetchUsers(); // 获取用户列表
    },
    methods: {
      async fetchStudents(params = {}) {
        try {
          const response = await getStudents({
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            ...params
          });
          this.students = response.rows;
          this.total = response.total;
        } catch (error) {
          console.error('Error fetching students:', error);
        }
      },
      handleSizeChange(newPageSize) {
        this.pageSize = newPageSize;
        this.fetchStudents(this.searchForm);
      },
      handleCurrentChange(newPage) {
        this.currentPage = newPage;
        this.fetchStudents(this.searchForm);
      },
      formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      },
      onSearch() {
        this.currentPage = 1; // 搜索时重置页码为第一页
        this.fetchStudents(this.searchForm);
      },
      openAddDialog() {
        if (this.newStudent.userId === '') {
          this.newStudent.userId = this.$store.state.user.id;
        }
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.newStudentForm.clearValidate(); // 清除表单验证
          this.resetNewStudent(); // 重置表单数据
        });
      },
      resetNewStudent() {
        this.newStudent = {
          userId: '',
          name: '',
          gender: '',
          university: '',
          major: '',
          college: '',
          birthDate: '',
          politicalStatus: '',
          healthStatus: '',
          nativePlace: '',
          enrollmentDate: '',
          contactAddress: ''
        };
      },
      addStudent() {
        this.$refs.newStudentForm.validate(async valid => {
          if (valid) {
            try {
              await saveOrUpdateStudent(this.newStudent);
              this.$message.success('学生信息添加成功');
              this.dialogVisible = false;
              this.fetchStudents(); // 刷新学生列表
            } catch (error) {
              console.error('Error adding student:', error);
            }
          } else {
            console.log('Validation failed!');
            return false;
          }
        });
      },
      handleEdit(index, row) {
        this.editingStudent = { ...row }; // 复制当前行的数据到编辑对象
        this.editDialogVisible = true;
        this.$nextTick(() => {
          this.$refs.editingStudentForm.clearValidate(); // 清除表单验证
        });
      },
      updateStudent() {
        this.$refs.editingStudentForm.validate(async valid => {
          if (valid) {
            try {
              await saveOrUpdateStudent(this.editingStudent);
              this.$message.success('学生信息更新成功');
              this.editDialogVisible = false;
              this.fetchStudents(); // 刷新学生列表
            } catch (error) {
              console.error('Error updating student:', error);
              this.$message.error('学生信息更新失败');
            }
          } else {
            console.log('Validation failed!');
            return false;
          }
        });
      },
      handleDelete(index, studentId) {
        this.$confirm('此操作将永久删除该学生信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await deleteStudent(studentId); // 调用删除接口
            this.$message.success('删除成功');
            this.fetchStudents(); // 刷新学生列表
          } catch (error) {
            console.error('Error deleting student:', error);
            this.$message.error('删除失败');
          }
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },
      async fetchUsers() {
        try {
          const response = await studentUserList(); // 使用新的API函数
          this.users = response.data;
        } catch (error) {
          console.error('Error fetching users:', error);
        }
      }
    }
  };
  </script>
  
  <style scoped>
  /* 可以在这里添加一些样式 */
  .app-container {
    padding: 20px;
  }
  .demo-form-inline {
    margin-bottom: 20px;
  }
  
  .custom-dialog .el-form-item__label {
    text-align: right;
  }
  
  .custom-dialog .el-form-item {
    margin-bottom: 20px;
  }
  
  .custom-dialog .el-col {
    padding-right: 10px;
    padding-left: 10px;
  }
  
  .right-column {
    padding-right: 30px; /* 增加右侧内边距 */
  }
  
  .uniform-input {
    width: 100%;
  }
  
  .action-button {
    color: #409EFF; /* 设置为蓝色字体 */
    cursor: pointer;
    text-decoration: underline;
    margin-right: 10px;
    border: none;
    background-color: transparent;
  }
  
  .delete-button {
    color: #F56C6C; /* 设置为红色字体 */
  }
  
  .action-button:hover {
    text-decoration: none;
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  </style>
  
  
  
  